import { openDB, closeDB, select, insert, update, remove } from '@/assets/database'
import { setVolume, getVolume } from '@/assets/js/native.js'
import { readAllLines } from '@/uni_modules/ybuts-filereader'
//音乐播放
const state = {
	context: null,//播放器正文
	currentIndex: 0,//播放索引
	currentTime: 0,//播放时间
	playlist: []//播放列表
}

const getters = {
	GET_CONTEXT (state) {
		return state.context
	},
	GET_CURRENT_INDEX (state) {
		return state.currentIndex
	},
	GET_CURRENT_TIME (state) {
		return state.currentTime
	},
	GET_PLAY_LIST (state) {
		return state.playlist
	}
}

const mutations = {
	SET_CONTEXT (state, context) {
		state.context = context
	},
	SET_CURRENT_INDEX (state, index) {
		state.currentIndex = index
	},
	SET_CURRENT_TIME (state, currentTime) {
		state.currentTime = currentTime
	},
	//设置播放列表
	SET_PLAY_LIST (state, playlist) {
		state.playlist = playlist
	}
}

const actions = {
	next ({state, dispatch}) {
		const length = state.playlist.length
		const currentIndex = parseInt(state.currentIndex)
		if ( length > 1 && currentIndex + 1 < length ) {
			dispatch('change', currentIndex + 1)
		} else {
			uni.showToast({
				title: '播放结束',
				icon: 'none'
			})
		}
	},
	async change ({state, commit, rootGetters, dispatch}, index) {
		const list = state.playlist
		if ( list[index] ) {
			const detail = list[index].detail
			const network = rootGetters['network/GET']
			//创建视频播放器
			const player = state.context || plus.webview.create('/hybrid/html/video/my-video-player.html', 'videoplayer', {
				additionalHttpHeaders: { 'Referer': 'uni-app' },
				position: 'absolute',
				left: '0px',
				width: '100%',
				height: '30%',
				softinputMode: 'adjustResize'
			})
			//如果是第一次加载需要绑定拦截事件
			if ( !state.context ) {
				player.overrideUrlLoading({ mode: 'reject' }, async (e) => {
				  const url = e.url;
				  // 解析参数
				  const lastIndex = url.lastIndexOf('?');
				  const paramsStr = url.slice(lastIndex + 1);
				  const paramsArr = paramsStr.split('&')
				  const params = {}
				  paramsArr.forEach(str => {
					  const chars = str.split('=')
					  params[chars[0]] = chars[1]
				  })
				  // 处理数据
				  if ( params.back == 1 ) {//销毁视频播放器
					plus.webview.close(player)
					commit('SET_CONTEXT', null)
				  }
				  if ( params.work) {//显示分P选择
				  	const pages = getCurrentPages()
				  	const page = pages[pages.length-1]
				  	page.$vm.showItems && page.$vm.showItems({
						title: '选集',
						data: state.playlist.map(s => s.item),
						current: state.currentIndex,
						defaultTitle: detail.title,
						unit: '集',
						success: res => {
							if ( res.confirm ) {
								dispatch('change', res.current)
							}
						}
					})
				  }
				  if ( params.next ) {//播放下一个视频
					dispatch('next')
				  }
				  if ( params.workChange ) {//切换分P
				  	dispatch('change', params.workChange)
				  }
				  if ( params.startDownload ) {//下载视频
				  	const pages = getCurrentPages()
					const page = pages[pages.length-1]
					page.$vm.download && page.$vm.download({title: decodeURIComponent(params.title), url: decodeURIComponent(params.src), isAdult: detail.isAdult})
				  }
				  //设置系统亮度
				  if ( params.seekLight >= 0) {
					uni.setScreenBrightness({
						value: params.seekLight
					})
				  }
				  //设置媒体音量
				  if ( params.seekVolume >= 0) {
					setVolume(params.seekVolume)
				  }
				  //增加弹幕过滤规则
				  if ( params.danmufilteradd ) {
					await openDB()
					try{
						const rule = JSON.parse(decodeURIComponent(params.danmufilteradd))
						await insert('danmufilter', {
							pattern: rule.pattern,
							type: rule.type
						})
						closeDB()
					}catch(e){
						closeDB()
						uni.showToast({
							title: e.message,
							icon: 'none'
						})
					}
				  }
				  //删除弹幕过滤规则
				  if ( params.danmufilterreduce ) {
				  	await openDB()
				  	try{
				  		const rule = JSON.parse(decodeURIComponent(params.danmufilterreduce))
				  		await remove('danmufilter', 'pattern = "' + rule.pattern + '" AND type = "' + rule.type + '"' )
				  		closeDB()
				  	}catch(e){
				  		closeDB()
				  		uni.showToast({
				  			title: e.message,
				  			icon: 'none'
				  		})
				  	}
				  }
				  // 阻止默认跳转行为
				  return true;
				});
			}
			//存储播放器
			commit('SET_CONTEXT', player)
			//请求视频正文
			const newItem = await getContext(network, list[index])
			//请求视频弹幕
			const barrages = await getBarrages(network, Object.assign({}, list[index], {item: newItem}))
			const src = newItem.src
			const title = newItem.title || newItem.name || detail.title
			const poster = newItem.poster || newItem.cover || detail.cover
			const type = ![undefined, null, ''].includes(newItem.type) ? newItem.type : (detail.type || '')
			const isLive = ![undefined, null, ''].includes(newItem.isLive) ? newItem.isLive : (detail.isLive || false)
			const autoplay = rootGetters['setting/GET_VIDEO_AUTOPLAY']
			commit('SET_CURRENT_TIME', 0)
			commit('SET_CURRENT_INDEX', index)
			
			//获取当前亮度
			const initialLight = await getLight()
			//获取当前音量
			const initialVolume = getVolume()
			//获取弹幕过滤规则
			await openDB()
			const data = await select('danmufilter', '', '')
			closeDB()
			var works = state.playlist.map(s => s.item)
			const arg = {src, title, poster, autoplay, type, barrages, isLive, initialLight, initialVolume, works, workIndex: index, danmufilter: data.list}
			player.evalJS(`setVideo('${encodeURIComponent(JSON.stringify(arg))}');`)
			if ( [0, 1].includes(rootGetters['setting/GET_HISTORY']) ) {
				await openDB()
				const data = await select('record', 'unique_id = "' + detail.uniqueId + '"')
				const record = data.list[0] || {}
				try{
					if ( record.id ) {
						await update('record', {
							url: detail.url,
							title: detail.title || '',
							cover: detail.cover || '',
							current: state.currentIndex,
							position: state.currentTime,
							currentTitle: title,
							is_adult: detail.isAdult,
							source_id: detail.sourceId
						}, 'id = ' + record.id)
					} else {
						await insert('record', {
							unique_id: detail.uniqueId,
							url: detail.url,
							title: detail.title || '',
							cover: detail.cover || '',
							current: state.currentIndex,
							position: state.currentTime,
							currentTitle: title,
							is_adult: detail.isAdult,
							source_id: detail.sourceId
						})
					}
					closeDB()
				}catch(e){
					closeDB()
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
				}
			}
			
		}
	}
}

const getContext = async function (network, video) {
	const context = video.context || {}
	const request = context.request
	const params = Object.assign({}, video.query, video.detail, video.item)
	const staticData = context.staticData ? await network.staticDataHandle(context.staticData, params) : {}
	const dynamicData = context.dynamicData || {}
	const newRequest = request ? await network.requestHandle(request, params) : null
	const response = newRequest ? await network.$request(newRequest) : {}
	const data = response.data ? await network.$list(dynamicData, response.data, response.taskId) : null
	return Object.assign({}, video.item, staticData, data)
}
const getBarrages = async function  (network, video) {
	const barrages = video.barrages || {}
	const params = Object.assign({}, video.query, video.detail, video.item)
	const staticData = barrages.staticData ? await network.staticDataHandle(barrages.staticData, params) : []
	const dynamicData = barrages.dynamicData
	const request = barrages.request
	let data = []
	if ( dynamicData && request ) {
		const newRequest = await network.requestHandle(request, params)
		const response = await network.$request(newRequest)
		data = await network.$list(dynamicData, response.data, response.taskId)
	}
	return staticData.concat(data)
}

const getLight = function () {
	return new Promise(resolve => {
		uni.getScreenBrightness({
			success: res => {
				resolve(res.value)
			}
		})
	})
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
	actions
}
